// 工具函数库

// 过期时间
const DAY = 864000;

function formatTime(time) {
	if (typeof time !== 'number' || time < 0) {
		return time
	}

	var hour = parseInt(time / 3600);
	time = time % 3600;
	var minute = parseInt(time / 60);
	time = time % 60;
	var second = time;

	return ([hour, minute, second]).map(function(n) {
		n = n.toString();
		return n[1] ? n : '0' + n
	}).join(':')
}

function formatLocation(longitude, latitude) {
	if (typeof longitude === 'string' && typeof latitude === 'string') {
		longitude = parseFloat(longitude);
		latitude = parseFloat(latitude)
	}

	longitude = longitude.toFixed(2);
	latitude = latitude.toFixed(2);

	return {
		longitude: longitude.toString().split('.'),
		latitude: latitude.toString().split('.')
	}
}

var dateUtils = {
	UNITS: {
		'年': 31557600000,
		'月': 2629800000,
		'天': 86400000,
		'小时': 3600000,
		'分钟': 60000,
		'秒': 1000
	},
	humanize: function(milliseconds) {
		var humanize = '';
		for (var key in this.UNITS) {
			if (milliseconds >= this.UNITS[key]) {
				humanize = Math.floor(milliseconds / this.UNITS[key]) + key + '前';
				break;
			}
		}
		return humanize || '刚刚';
	},
	format: function(dateStr) {
		var date = this.parse(dateStr);
		var diff = Date.now() - date.getTime();
		if (diff < this.UNITS['天']) {
			return this.humanize(diff);
		}
		var _format = function(number) {
			return (number < 10 ? ('0' + number) : number);
		};
		return date.getFullYear() + '/' + _format(date.getMonth() + 1) + '/' + _format(date.getDay()) + '-' +
			_format(date.getHours()) + ':' + _format(date.getMinutes());
	},
	parse: function(str) { //将"yyyy-mm-dd HH:MM:ss"格式的字符串，转化为一个Date对象
		var a = str.split(/[^0-9]/);
		return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
	}
};

//将音乐的秒钟转为分钟 04.25
function secondToMinute(time) {
	time = parseInt(time / 1000); //转为秒数
	var minute = parseInt(time / 60);
	minute = minute < 10 ? '0' + minute : minute;
	var second = time % 60;
	second = second < 10 ? '0' + second : second;
	return minute + '.' + second;
}

// 将秒转换为时分秒
function formatSeconds(value) {
	// var secondTime = parseInt(value);// 秒
	var secondTime = value; // 秒
	var minuteTime = 0; // 分
	var hourTime = 0; // 小时
	if (secondTime > 60) { //如果秒数大于60，将秒数转换成整数
		//获取分钟，除以60取整数，得到整数分钟
		minuteTime = parseInt(secondTime / 60);
		//获取秒数，秒数取佘，得到整数秒数
		secondTime = parseInt(secondTime % 60);
		//如果分钟大于60，将分钟转换成小时
		if (minuteTime > 60) {
			//获取小时，获取分钟除以60，得到整数小时
			hourTime = parseInt(minuteTime / 60);
			//获取小时后取佘的分，获取分钟除以60取佘的分
			minuteTime = parseInt(minuteTime % 60);
		}
	}
	var result = `${PrefixInteger(parseInt(secondTime), 2)}`;

	if (minuteTime > 0) {
		result = `${PrefixInteger(parseInt(minuteTime), 2)}：${result}`;
	} else {
		result = `00:${result}`;
	}
	if (hourTime > 0) {
		result = `${PrefixInteger(parseInt(hourTime), 2)}：${result}`;
	}
	return result;
}
// 将秒转换为天时分秒
function formatDay(value) {
	var secondTime = parseInt(value); // 秒
	// var secondTime = value / 1000; // 秒
	var minuteTime = 0; // 分
	var hourTime = 0; // 小时
	var day = 0; // 天
	if (secondTime > 60) { //如果秒数大于60，将秒数转换成整数
		//获取分钟，除以60取整数，得到整数分钟
		minuteTime = parseInt(secondTime / 60);
		//获取秒数，秒数取佘，得到整数秒数
		secondTime = parseInt(secondTime % 60);
		//如果分钟大于60，将分钟转换成小时
		if (minuteTime > 60) {
			//获取小时，获取分钟除以60，得到整数小时
			hourTime = parseInt(minuteTime / 60);
			//获取小时后取佘的分，获取分钟除以60取佘的分
			minuteTime = parseInt(minuteTime % 60);
		}
		if (hourTime > 24) {
			day = parseInt(hourTime / 24);
			hourTime = parseInt(hourTime % 24);
		}
	}
	var result = PrefixInteger(parseInt(secondTime), 2);
	if (minuteTime > 0) {
		result =
			`${PrefixInteger(parseInt(minuteTime), 2)}分${result}秒`;
	} else {
		result = `${result}秒`;
	}
	if (hourTime > 0) {
		result = `${PrefixInteger(parseInt(hourTime), 2)}小时${result}`;
	}
	result = `${PrefixInteger(parseInt(day), 2)}天${result}`;
	return result;
}
// 补零
function PrefixInteger(num, m) {
	return isNaN((Array(m).join(0) + num).slice(-m)) ? '00' : (Array(m).join(0) + num).slice(-m)
};
//toast提示信息
function showToast(title, icon = 'none') {
	uni.showToast({
		title,
		icon
	});
}
//根据key获取storage
function getLocalStorage(key) {
	return uni.getStorageSync(key);
}

//根据key删除storage
function removeLocalStorage(key) {
	return uni.removeStorageSync(key);
}

//根据key value设置storage
function setLocalStorage(key, value) {
	uni.setStorageSync(key, value);
}

function adornUrl(actionName) {
	return '/proxyApi' + actionName
}

function setNavTitle(title) {
	if (title) {
		uni.setNavigationBarTitle({
			title: title,
			fail(err) {
				this.setNavTitle(val)
			}
		})
	}
}

function setNavLogo(logo) {
	if (logo) {
		let height = plus.navigator.getStatusbarHeight()
		var view = new plus.nativeObj.View("test", {
			top: `${height}px`,
			left: "0px",
			height: '44px',
			width: "45px"
		});
		// 绘制图片
		view.draw([{
			tag: "img",
			id: "img",
			src: logo,
			position: {
				top: "auto",
				left: "20px",
				width: "25px",
				height: "25px"
			}
		}]);
		return view;
	}
}

function richText(val) {
	return val.replace(/<figure class="image">/gi, '').replace(/<\/figure>/gi, '').replace(/<img/gi,
		'<img style="max-width:100%;height:auto;display:block" ').replace(/&nbsp;/gi,
		'<span style="display: inline-block; width: .28em"></span>').replace(/<mark /gi, '<span ').replace(/<\/mark>/gi,
		'</span>').replace(/<s>/gi, ' <del>').replace(/<\/s>/gi, ' </del>').replace(/<u>/gi, '<ins>').replace(/<\/u>/gi,
		'</ins>')
}

function showModal(res, _this) {
	uni.showModal({
		title: '有新版本发布了，请确认更新？',
		content: res.log[0],
		showCancel: !res.forceUpdate,
		cancelText: '稍后更新',
		confirmText: '立即更新',
		success: function(button) {
			if (button.confirm) {
				_this.download = true;
				_this.$nextTick(function() {
					_this.$refs.downloadApk.downloadApk(res);
				});
			} else if (button.cancel) {
				uni.setStorageSync('updata', 'no');
			} else {
				showModal(res, _this);
			}
		},
		fail: function() {
			showModal(res, _this);
		}
	});
}
export {
	showModal,
	setNavTitle,
	setNavLogo,
	formatTime,
	formatLocation,
	dateUtils,
	showToast,
	getLocalStorage,
	removeLocalStorage,
	setLocalStorage,
	secondToMinute,
	adornUrl,
	formatSeconds,
	PrefixInteger,
	formatDay,
	richText
};
